//声明订单详情对象
var orderObj;
//用户id，从localStorage获取
var userId=localStorage.getItem("userId");
$(function () {
    if(!localStorage.getItem("addressId")){
        $('.address_choose').html($("#blankAddContain").html());
    }else {
        $.ajax({
            url:'http://api.qujiamall.com/User/GetAddressList?user_id='+userId,
            type:'get',
            dataType:'json',
            async:'false',
            success:function (json) {
                $.each(json.data,function (index,elem) {
                    if(elem.address_id==localStorage.getItem("addressId")){
                        var checkedAdd = Handlebars.compile($("#checkedAddContain").html());
                        $('.address_choose').html(checkedAdd(elem));
                    }
                });
                $(".address_choose").find(".address").attr("data-addressId",localStorage.getItem("addressId"));
                // 清空地址id的localStorage
                localStorage.setItem("addressId","");
            }
        });
    }
    //初始化页面订单信息
    orderObj={
        goodsId:GetQueryString("goodsId"),
        skuId:GetQueryString("skuId"),
        thumbUrl:GetQueryString("thumbUrl"),
        salePrice:GetQueryString("salePrice"),
        summary:decodeURI(decodeURI(GetQueryString("summary"))),
        spcText:decodeURI(decodeURI(GetQueryString("spcText"))),
        godsNum:GetQueryString("godsNum"),
        orderGroupId:GetQueryString("order_group_id"),
        payType:1
    };
    var orderDetail = Handlebars.compile($("#orderDetail").html());
    $(".orderDetail").html(orderDetail(orderObj));
    $(".value").val(orderObj.godsNum);
    //总价格
    $(".bottomBtn").find(".allPrice").text(orderObj.godsNum*orderObj.salePrice);

    //选择支付方式
    $(".payCho").on("click",function (event) {
        $(event.target).siblings().find(".rhContain").hide();
        $(event.target).find(".rhContain").show();
        orderObj.payType=$(this).attr("data-paytype");
        orderObj.payTypeName=$(this).find(".payTypeName").text();
        console.log($(this).find(".payTypeName").text());
    });
    //立即购买（确认支付）
    $(".doPay").click(function () {
        //获取地址信息
        var addressChecked=$(".address_choose").find(".address").attr("data-addressId");
        if(!addressChecked){
            layer.msg("请选择地址");
            return;
        }
        //获取平台信息
        var platformType;
        if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
            platformType=2;
        } else if (/(Android)/i.test(navigator.userAgent)) {
            platformType=3;
        } else {
            platformType=1;
        }
        //创建订单
        $.ajax({
            url:'http://api.qujiamall.com/Order/AddOrder',
            type:'POST',
            dataType:"JSON",
            data:{
                "order_group_id": orderObj.orderGroupId,
                "goods_id": orderObj.goodsId,
                "sku_id": orderObj.skuId,
                "user_coupon_id": 0,
                "buy_type": 2,
                "quantity": orderObj.godsNum,
                "address_id": addressChecked,
                "pay_type": orderObj.payType,
                "platform_type": platformType,
                "user_id": userId
            },
            async : true,
            success:function(json){
                if(json.code==1){
                    //弹出订单支付信息
                    var allMoney=$(".bottomBtn").find(".truePay").find(".allPrice").text();
                    var payType=orderObj.payTypeName;
                    $('.maskContain').html($("#sureMask").html()).show();
                    $(".surePay").find(".pay_num").find(".text_money").text(allMoney);
                    $(".surePay").find(".pay_sty").find(".fr").text(payType);
                    // 判断订单号是否存在,调用立即支付功能
                    if(json.data.order_no){
                        $(".sureBtn").bind("click",function () {
                            if(orderObj.payType==1){
                                $('.maskContain').html($("#passwordMask").html());
                                var keyboard = document.querySelector('.keyboard').querySelectorAll('li');
                                for(var i = 0 ; i < keyboard.length; i++){
                                    keyboard[i].addEventListener('click',function(){
                                        set_num($(this).attr("data-index"))
                                    },false);
                                }
                                function set_num(num){
                                    var spans = document.querySelector('.password').querySelectorAll('span');
                                    if(/[0-9]/.test(num)){
                                        var index = 0;
                                        for(var i = 0; i < spans.length; i++){
                                            var val = spans[i].innerHTML;
                                            index = i;
                                            if(!val){
                                                spans[i].innerHTML = num;
                                                spans[i].setAttribute('data-num',num);
                                                setTimeout(function(){
                                                    spans[i].innerHTML = '*';
                                                },200);
                                                break;
                                            }
                                        }
                                        if(index == 5){
                                            var password = '';
                                            for(var j = 0; j < spans.length; j++){
                                                var val = spans[j].getAttribute('data-num');
                                                password += val;
                                            }
                                            // alert(password);
                                            closeMask();
                                            window.location.href="payFinish.html";
                                            setTimeout(function(){
                                                for(var k = 0; k < spans.length; k++){
                                                    spans[k].innerHTML = '';
                                                    spans[k].setAttribute('data-num','');
                                                }
                                            },300);
                                        }
                                    }else if(num == 'delete'){
                                        var index = 0;
                                        for(var i = 0; i < spans.length; i++){
                                            var val = spans[i].innerHTML;
                                            if(val){
                                                index = i;
                                            }
                                        }
                                        spans[index].innerHTML = '';
                                        spans[index].setAttribute('data-num','');
                                    }

                                }
                            }else if(orderObj.payType==2){
                                $.ajax({
                                    url:"http://api.qujiamall.com/Order/GetPayOrder?user_id="+userId+"&pay_type=2&order_no="+json.data.order_no,
                                    type:'get',
                                    dataType:'json',
                                    async:'false',
                                    success:function (json) {
                                        console.log(JSON.parse(json.data));
                                        var httparams=JSON.parse(json.data);
                                        if(json.code==1){
                                            function onBridgeReady(){
                                                WeixinJSBridge.invoke(
                                                    'getBrandWCPayRequest', {
                                                        "appId":httparams.appid,     //公众号名称，由商户传入
                                                        "timeStamp":httparams.timestamp,         //时间戳，自1970年以来的秒数
                                                        "nonceStr":httparams.noncestr, //随机串
                                                        "package":httparams.package,
                                                        "signType":"MD5",         //微信签名方式：
                                                        "paySign":httparams.sign //微信签名
                                                    },
                                                    function(res){
                                                        if(res.err_msg == "get_brand_wcpay_request:ok" ){
                                                            // 使用以上方式判断前端返回,微信团队郑重提示：
                                                            //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
                                                            alert(res.err_msg);
                                                        }else{
                                                            alert(res.err_msg);
                                                        }
                                                    });
                                            }
                                            if (typeof WeixinJSBridge == "undefined"){
                                                if( document.addEventListener ){
                                                    document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
                                                }else if (document.attachEvent){
                                                    document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
                                                    document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
                                                }
                                            }else{
                                                onBridgeReady();
                                            }
                                        }
                                    }
                                });
                                console.log("微信支付");
                            }else {
                                console.log("支付宝支付");
                            }
                        })
                    }
                }else {
                    layer.msg(json.msg);
                }
            }
        });
    });
    //改变商品数量
    $(".increase").click(function () {
        var num = $(".value").val();
        num++;
        $(".value").val(num);
        $(".bottomBtn").find(".allPrice").text(num*orderObj.salePrice);
    });
    $(".decrease").click(function () {
        var num = $(".value").val();
        num--;
        if(num<1){
            return;
        }
        $(".value").val(num);
        $(".bottomBtn").find(".allPrice").text(num*orderObj.salePrice);
    });
});
// 输入密码返回到确认支付
function gobackPay() {
    $('.maskContain').html($("#sureMask").html()).show();
}
//关闭蒙版
function closeMask() {
    $('.maskContain').hide();
}
